<?php

namespace Admin\Controller;

use Think\Controller;

class TimerController extends Controller
{

    /**
     * 每天凌晨执行,渠道统计
     */
    public function channel_day()
    {
        $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $endYesterday = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $where1 = ['between', [$beginYesterday, $endYesterday]];
        $entry = M('user_login', '', 'XYC')->where(['channel' => ['neq', ''], 'ctime' => $where1])->group('channel')->getfield('channel,count(id) as num', true);
        $cert = M('user', '', 'XYC')->where(['channel' => ['neq', ''], 'cert_status' => 2, 'cert_time' => $where1])->group('channel')->getfield('channel,count(id) as num', true);
        $borrow_where = ['channel' => ['neq', ''], 'status' => ['in', '2,3,4,5,6,9'], 'loan_time' => $where1];
        $borrow_order = M('certificate', '', 'XYC')->where($borrow_where)->group('channel')->getfield('channel,count(id) as num', true);
        $item = M('certificate', '', 'XYC')->where($borrow_where)->group('borrower_id')->field('channel,borrower_id,1 as num')->select();
        $borrow_user = [];
        foreach ($item as $k => $v) {
            if (!isset($borrow_user[$v['channel']])) {
                $borrow_user[$v['channel']] = $v['num'];
            } else {
                $borrow_user[$v['channel']] += $v['num'];
            }
        }
        if (empty($where['state'])) {
            $where['state'] = ['neq', -1];
        }
        $arr = [];
        $list = M('channel', '', 'XYC')->WHERE($where)->field('chan_id,channel_name,shop_identifier')->ORDER("id desc")->SELECT();
        foreach ($list as $k => $v) {
            $list[$k]['entry'] = empty($entry[$v['chan_id']]) ? 0 : $entry[$v['chan_id']];
            $list[$k]['cert'] = empty($cert[$v['chan_id']]) ? 0 : $cert[$v['chan_id']];
            $list[$k]['borrow_user'] = empty($borrow_user[$v['chan_id']]) ? 0 : $borrow_user[$v['chan_id']];
            $list[$k]['borrow_order'] = empty($borrow_order[$v['chan_id']]) ? 0 : $borrow_order[$v['chan_id']];
            $list[$k]['type'] = 1;
            $list[$k]['ctime'] = $beginYesterday;
            $list[$k]['shop_identifier'] = $v['shop_identifier'];
            $list[$k]['chan_id'] = $v['chan_id'];
            array_push($arr, $list[$k]);
        }
        if (count($arr) > 0) {
            if (M('channel_statis', '', 'XYC')->addall($arr)) {
                echo '成功';
                die;
            } else {
                echo '失败';
                die;
            }
        } else {
            echo '无需要添加的数据';
            die;
        }
    }


    /**
     * 总数据统计
     * 每小时统计一次
     */
    public function all_data_statistics()
    {
        //总用户数、总逾期人数、总借款人数、总借款金额、总借款订单数、总收入、总还款金额、总逾期金额、总逾期笔数、总逾期率
//        凭证状态，0待支付,1未确认,2已确认,3已逾期,4续期,5已坏账,6已撕毁,7被拒绝,9已打款
        $merchant_db = M('merchant', '', 'XYC');
        $user_db = M('user', '', 'XYC');
        $certificate_db = M('certificate', '', 'XYC');
        $certificate_period_db = M('certificate_period', '', 'XYC');
        $shop_all_data_statistics_db = M('shop_all_data_statistics', '', 'XYC');
        $shop_list = $merchant_db->WHERE(['status' => '1'])->getField('shop_identifier', true);
        foreach ($shop_list as $k => $v) {
            $all_overdue_user = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => '3'])->GROUP("borrower_id")->FIELD('borrower_id')->SELECT();
            $all_borrow_user = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => ['in', ['2', '3', '4', '5', '6', '9']]])->GROUP("borrower_id")->FIELD('borrower_id')->SELECT();
            $all_borrow_money = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => ['in', ['2', '3', '4', '5', '6', '9']]])->SUM('money');
            $all_income_1 = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => ['in', ['2', '3', '4', '5', '6', '9']]])->SUM('interest');
            $all_income_1 = !empty($all_income_1) ? $all_income_1 : 0;
            $all_income_2 = $certificate_period_db->WHERE(['shop_idenfier' => $v, 'status' => '2'])->SUM('interest');
            $all_income_2 = !empty($all_income_2) ? $all_income_2 : 0;
            $all_repayment_money = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => '6'])->SUM('real_repayment_money');
            $all_waiting_repayment_money = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => ['in', ['2', '3', '4', '5', '9']]])->SUM('money');
            $all_overdue_money = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => '3'])->SUM("money");//总逾期金额

            $data['shop_identifier'] = $v;
            $data['all_user'] = $user_db->WHERE(['shop_identifier' => $v])->COUNT();//总用户数
            $data['all_overdue_user'] = count($all_overdue_user);//总逾期人数
            $data['all_borrow_user'] = count($all_borrow_user);//总借款人数
            $data['all_borrow_money'] = !empty($all_borrow_money) ? $all_borrow_money : 0;//总借款金额
            $data['all_borrow_num'] = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => ['in', ['2', '3', '4', '5', '6', '9']]])->COUNT();//总借款订单数
            $data['all_income_money'] = $all_income_1 + $all_income_2;//总收益
            $data['all_repayment_money'] = !empty($all_repayment_money) ? $all_repayment_money : 0;//总还款金额
            $data['all_wait_repayment_money'] = !empty($all_waiting_repayment_money) ? $all_waiting_repayment_money : 0;//总待还款金额
            $data['all_overdue_money'] = !empty($all_overdue_money) ? $all_overdue_money : 0;//总逾期金额
            $data['all_overdue_num'] = $certificate_db->WHERE(['shop_identifier' => $v, 'status' => '3'])->COUNT();//总逾期笔数
            $data['all_overdue_rate'] = round($data['all_overdue_num'] / $data['all_borrow_num'], 2);//总逾期率
            $check = $shop_all_data_statistics_db->WHERE(['shop_identifier' => $v])->getField('id');
            if (!empty($check)) {
                $data['upd_time'] = time();
                $shop_all_data_statistics_db->WHERE(['shop_identifier' => $v])->save($data);
            } else {
                $data['ctime'] = time();
                $shop_all_data_statistics_db->add($data);
            }
            var_dump($data);
        }
    }

    /**
     * 凌晨 未还款逾期订单天数 滞纳金 增加  还要判断续期情况
     */
    public function payment_order()
    {
        //逾期加1
        //滞纳金增加
        $where = [];
        $where['a.status'] = 1;
        $where['a.version'] = 'v2';
        $where['a.type'] = ['eq', 1];
        $where['a.ctime'] = array('lt', time() - 3);//防止把当天生成的逾期订单重复计算
        $field = 'a.id,a.shop_identifier,a.param_id,a.numbering,a.repayment_money,a.overdue_day,b.repayment_amount';
        $orders = M('user_overdue', '', 'XYC_SERVICE')->join('a join xyc.vz_loan b on b.order_number=a.numbering')->where($where)->field($field)->select();

        if (empty($orders)) {
            die;
        }
        //参数值
        $param_arr = array_flip(array_column($orders, 'param_id'));//键值去重
        $param_arr = array_flip($param_arr);
        $param = M('merchant_param_record', '', 'XYC')->where(['in' => $param_arr])->getfield('id,late_fee,late_days', true);
        //天数增加
        M('user_overdue', '', 'XYC_SERVICE')->alias('a')->where($where)->setInc('overdue_day', 1);
        $arr = [];
        foreach ($orders as $k => $v) {
            //是否结束计算罚金
            if ($v['overdue_day'] < $param[$v['param_id']]['late_days']) {
                $fine = floor((($v['repayment_money'] - $v['repayment_amount']) * ($param[$v['param_id']]['late_fee'] / 10000)) * 100) / 100;
                $fine = $fine <= 0 ? 0.5 : $fine;
                $arr[$v['numbering']] = $fine;
                M('vz_loan', '', 'XYC')->where(['order_number' => $v['numbering']])->setInc('overdue_money', $fine);//订单表罚金增加
                M('user_overdue', '', 'XYC_SERVICE')->where(['numbering' => $v['numbering']])->setInc('overdue_money', $fine);//逾期表罚金增加
            } else {
                M('user_overdue', '', 'XYC_SERVICE')->where($where)->setfield('type', 3);//
            }
        }

        add_control_log(1, '系统', date('Y-m-d', time()) . '逾期订单天数/罚金增加');
        echo 1;
    }

    /**
     * 凌晨 逾期订单添加
     * 逾期订单增加
     * 订单表 状态修改，罚金数额修改
     */
    public function add_overdue()
    {
        $e_time = time() - 10;//以免将当天应该还款的给变成逾期的
        $order = M('vz_loan', '', 'XYC')->where(['status' => 1, 'time_renewal' => ['elt', 1], 'atlast_time' => ['lt', $e_time]])->field('user_id,order_number,loan_amount,shop_identifier,atlast_time,param_id,repayment_amount')->select();
//      var_dump($order);die;

        //设置订单已逾期
        M('vz_loan', '', 'XYC')->where(['status' => 1, 'time_renewal' => ['elt', 1], 'atlast_time' => ['lt', $e_time]])->save(['status' => 3]);
        $arr = array();
        //罚金参数
        $fine_param = M('merchant_param_record', '', 'XYC')->where(['id' => ['in', array_column($order, 'param_id')]])->getfield('id,late_fee', true);
        foreach ($order as $k => $v) {
            $fine_s = $fine_param[$v['param_id']];
            //罚金
            $fine = floor(($v['loan_amount'] - $v['repayment_amount']) * ($fine_s / 10000) * 100) / 100;//总金额-已还金额 乘以 罚金比例

            if ($fine < 0 && $fine_s != 0) {

//                continue;
                $fine = 0.5;
            }
            M('vz_loan', '', 'XYC')->where(['order_number' => $v['order_number']])->setfield('overdue_money', $fine);
            $arr[] = array('user_id' => $v['user_id'],
                'numbering' => $v['order_number'],
                'repayment_money' => $v['loan_amount'],
                'should_time' => $v['atlast_time'],
                'overdue_day' => 1,
                'overdue_money' => $fine,
                'version' => 'v2',
                'param_id' => $v['param_id'],
                'shop_identifier' => $v['shop_identifier'],
                'ctime' => time());
        }

//        var_dump($arr);
//        die;
        if (empty($arr)) {
            add_control_log(1, '系统', date('Y-m-d', $e_time) . '无逾期逾期订单');

            echo 1;
            die;
        }
        $add = M('user_overdue', '', 'XYC_SERVICE')->addAll($arr);
        if ($add) {

            add_control_log(1, '系统', date('Y-m-d', $e_time) . '逾期订单生成成功' . $add);
        } else {
            add_control_log(1, '系统', date('Y-m-d', $e_time) . '逾期订单生成失败');
        }
        echo 1;
    }


    /**
     * 续期订单到期修改   要在订单产生（add_overdue）逾期之前执行，因为都是凌晨执行 ，可能会有漏掉的逾期订单
     */
    public function renewal_order()
    {

        $where['a.time_renewal'] = ['between', [2, time() - 24 * 3600]];
        $overdue_orders = M('vz_loan', '', 'XYC')->where($where)->field('time_renewal,status')->select();

        if (!empty($overdue_orders)) {
            //续期时间更改
            M('vz_loan', '', 'XYC')->where($where)->setfield('time_renewal', 1);//1表示订单曾有过续期
            $order_arr = [];
            foreach ($overdue_orders as $k => $v) {
                switch ($v['status']) {
                    case 1://未还款
                        break;
                    case 2://已还款
                        break;
                    case 3://已逾期
                        $order_arr[] = $v['order_number'];
                        break;
                }
            }
            if ($order_arr) {
                $update = M('user_overdue', '', 'XYC')->where(['numbering' => ['in', $order_arr]])->setfield('status', 1);
            } else {
                add_control_log(1, '系统', date('Y-m-d', time()) . '无续期订单状态修改');
                die;
            }


            if ($update) {
                add_control_log(1, '系统', date('Y-m-d', time()) . '订单续期状态修改成功' . $update);
            } else {
                add_control_log(1, '系统', date('Y-m-d', time()) . '订单续期状态失败');
            }
        }

        //续期的归于正常后
        $this->add_overdue();

    }

    /***
     * 日息每天增加
     */
    public function day_interest()
    {
        $where['status'] = 1;
        $where['is_success'] = 2;
        $where['day_interest_money'] = ['gt', 0];
        $where['atlast_time'] = ['elt', time()];
        $data = M('vz_loan', '', 'XYC')->where($where)->field('id,param_id,loan_amount')->select();
        $p_id = array_flip(array_column($data, 'param_id'));
        $p_id = array_flip($p_id);

        $param=M('merchant_param_record','','XYC')->where(['id'=>['in',$p_id]])->getfield('id,day_interest',true);

        foreach ($data as $k => $v) {
            $money=floor($v['loan_amount']*($param[$v['param_id']]/100)*100)/100;
            M('vz_loan', '', 'XYC')->where(['id'=>$v['id']])->setInc('day_interest_money',$money);

        }
        add_control_log(1, '系统', date('Y-m-d H:i', time()) . '日息每天增加');


    }


    public function timer_zzc_up_data()
    {
        OftenController::zzc_up_data();
    }
    public function get_balance(){
        $url = 'https://pay.dstlkj.com/External/external_get_jd_balance';
        $data['xycjd'] = 'xycjd';
        $result = $this->curl_post_https($url,$data);
        $result = json_decode($result,true);
        var_dump( $result);
        // var_dump($result);

    }
    function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式

    }


    public  function add_money(){
//     $update=   M('merchant','','XYC')->where(['shop_identifier'=>'0100030043'])->setInc('withhold_balance',49600);
       $p= M('merchant','','XYC')->where(['shop_identifier'=>'0100030043'])->find();
     var_dump($p);
    }

 }